package com.luty.rpc.register;

import org.I0Itec.zkclient.ZkClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

/**
 * Created by liuyunxin on 2017/7/1.
 */
public class ServiceDiscover {
    private static final Logger LOGGER = LoggerFactory.getLogger(ServiceDiscover.class);
    private String zkAddress;

    public ServiceDiscover(String zkAddress){
        this.zkAddress = zkAddress;
    }

    public String discover(String name){
        ZkClient zkClient = new ZkClient(zkAddress, Constant.ZK_SESSION_TIME, Constant.ZK_CONNETCTION_TIMEOUT);
        LOGGER.debug("connect zookeeper");

        try{
            //获取 service node
            String servicePath = Constant.ZK_REGISTER_NAME + "/" + name;
            if(!zkClient.exists(servicePath)){
                throw new RuntimeException(String.format("can not find any service node on path: %s",servicePath));
            }
            List<String> addressList = zkClient.getChildren(servicePath);
            if(addressList.isEmpty()){
                throw new RuntimeException(String.format("can not find any address node on path: %s", servicePath));
            }

            String address;
            int size = addressList.size();
            LOGGER.debug("addressList size:{}",size);
            for (int i=0; i<size; i++){
                LOGGER.debug(i + ":"+addressList.get(i));
            }
            if(size == 1) {
                address = addressList.get(0);
                LOGGER.debug(String.format("get address: ", address));
            }else {
                address = addressList.get(ThreadLocalRandom.current().nextInt(size));
                LOGGER.debug("get random address node: {}", address);
            }

            String addressPath = servicePath + "/" + address;
            return zkClient.readData(addressPath);
        }finally {
            zkClient.close();
        }
    }
}
